import axios from 'axios'
import { ElMessage } from 'element-plus'

// 全局使用的request，统一处理请求失败的操作

function reportError(msg) {
  console.error(msg)
  ElMessage({
    message: msg,
    type: 'error',
    duration: 5000
  })
}

function handleResponse(response, resolve, reject) {
  if (response.status != 200) {
    reportError('网络错误，代码：' + response.status)
    reject()
    return
  }
  var res = response.data
  if (res.code >= 200) {
    reportError('请求失败，错误信息：' + (res.error ?? res.data))
    reject()
    return
  }

  resolve(res)
}

function handleError(error) {
  reportError("未知错误：" + error.message)
}

export default {
  get(url, params = {}) {
    return new Promise((resolve, reject) => {
      params.token = getToken()
      axios.get(url, {
        params: params
      })
      .then(response => handleResponse(response, resolve, reject))
      .catch(error => {
        handleError(error)
        reject()
      })
    })
  },
  post(url, form = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, form)
      .then(response => handleResponse(response, resolve, reject))
      .catch(error => {
        handleError(error)
        reject()
      })
    })
  }
}
